import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Modal, Input, Row, Col, message, Divider, Dropdown, Menu } from 'antd';
import queryString from 'query-string';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import { mgrAxios } from '@/utils/utils'; // 引入字典
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Supplier from '../../components/NsSupplier';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ login, supplierview, loading }) => ({
  baseUser: login.baseUser,
  pageData: supplierview.pageData,
  loading: loading.effects['supplierview/getPageList'],
  formFieldsValue: supplierview.formFieldsValue,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    const {
      pageData: { pagination },
      location,
      dispatch,
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    const { queryParam } = location;
    dispatch({
      type: 'supplierview/updateModelData',
      payload: {},
    });
    if (isMenuLink === 'true') {
      this.resetAndGeLlist(location);
    } else if (isMenuLink === 'false') {
      if (queryParam) {
        dispatch({
          type: 'supplierview/updateModelData',
          payload: {
            formFieldsValue: queryParam,
          },
        });
      }
      this.getList(pagination.current, pagination.pageSize, queryParam);
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
  }

  // 获取数据
  getList = (currentPage = 1, pageSize = 10, queryParam, isClear = true) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch, form } = this.props;
    const fieldsValue = form.getFieldsValue();
    const tempFieldsValue = queryParam || fieldsValue;
    const formFieldsValue = {};
    Object.keys(tempFieldsValue).forEach(key => {
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
    });
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };
    dispatch({
      type: 'supplierview/getPageList',
      payload: values,
    });
  };

  // 查询列表
  searchList = () => {
    const { dispatch, form, pageData } = this.props;
    this.state.selectedRowKeys = [];
    this.state.selectedRows = [];
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      dispatch({
        type: 'supplierview/updateTabListQuery',
        payload: { formFieldsValue: values },
      });
      this.getList(pageData.pagination.current, pageData.pagination.pageSize);
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize, undefined, false);
  };

  // 重置查询
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'supplierview/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  // 查看详情
  goDetails = (id, name) => {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/detail?suppId=${id}&name=${name}`);
  };

  // 删除
  delList = suppId => {
    this.setState({ selectedRowKeys: [suppId] });
    const {
      pageData: { pagination },
    } = this.props;
    confirm({
      title: '你确定要删除此条供应商信息吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        mgrAxios('/suppBusiScope/delete', { suppIdList: [suppId] }) // supplier/deleteMul
          .then(res => {
            if (res.success) {
              message.success('删除成功！');
              this.getList(pagination.current, pagination.pageSize);
            } else {
              message.warning('删除失败！');
            }
          });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch } = this.props;
    dispatch({
      type: 'supplierview/updateModelData',
      payload: { expandForm: false },
    });
    await this.resetSearch();
    await this.getList();
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  render() {
    const { selectedRows, selectedRowKeys } = this.state;
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      pageData,
      loading,
    } = this.props;
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const columns = [
      {
        title: '供应商编号',
        dataIndex: 'suppCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '供应商名称',
        dataIndex: 'name',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '地区数量',
        dataIndex: 'areaSize',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        align: 'center',
      },
      {
        title: '供应商类型',
        dataIndex: 'typeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: 'companyDes',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => {
          const { baseUser } = this.props;
          const { userType } = baseUser;
          return (
            <div>
              {userType !== 1 ? (
                <span>
                  {record.type === 1 || record.type === 2 ? (
                    <Dropdown
                      overlay={
                        <Menu>
                          <Menu.Item>
                            <a onClick={() => this.goDetails(record.suppId, record.name)}>查看</a>
                          </Menu.Item>
                        </Menu>
                      }
                    >
                      <a>
                        更多 <DownOutlined />
                      </a>
                    </Dropdown>
                  ) : (
                    <div>
                      <Authorized authority="business:suppBusiScope:update" noMatch={null}>
                        <a
                          onClick={() =>
                            router.push(
                              `/supplymanage/busiscope/update?suppId=${record.suppId}&name=${
                                record.name
                              }&corpId=${record.corpId}`
                            )
                          }
                        >
                          修改
                        </a>
                        <Divider type="vertical" />
                      </Authorized>
                      <Dropdown
                        overlay={
                          <Menu>
                            <Menu.Item>
                              <a onClick={() => this.goDetails(record.suppId, record.name)}>查看</a>
                            </Menu.Item>
                            {checkPermissions('business:suppBusiScope:delete') && (
                              <Menu.Item>
                                <a onClick={() => this.delList(record.suppId)}>删除</a>
                              </Menu.Item>
                            )}
                          </Menu>
                        }
                      >
                        <a>
                          更多 <DownOutlined />
                        </a>
                      </Dropdown>
                    </div>
                  )}
                </span>
              ) : (
                <div>
                  <Authorized authority="business:suppBusiScope:update" noMatch={null}>
                    <a
                      onClick={() =>
                        router.push(
                          `/supplymanage/busiscope/update?suppId=${record.suppId}&name=${
                            record.name
                          }&corpId=${record.corpId}`
                        )
                      }
                    >
                      修改
                    </a>
                    <Divider type="vertical" />
                  </Authorized>
                  <Dropdown
                    overlay={
                      <Menu>
                        <Menu.Item>
                          <a onClick={() => this.goDetails(record.suppId, record.name)}>查看</a>
                        </Menu.Item>
                        {checkPermissions('business:suppBusiScope:delete') && (
                          <Menu.Item>
                            <a onClick={() => this.delList(record.suppId)}>删除</a>
                          </Menu.Item>
                        )}
                      </Menu>
                    }
                  >
                    <a>
                      更多 <DownOutlined />
                    </a>
                  </Dropdown>
                </div>
              )}
            </div>
          );
        },
      },
    ];
    const renderSimpleForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="供应商编号">
              {getFieldDecorator('suppCode', {
                initialValue: formFieldsValue.suppCode,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="供应商名称">
              {getFieldDecorator('suppId', {
                initialValue: formFieldsValue.suppId,
              })(<Supplier allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={this.searchList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{renderSimpleForm}</div>
        </Card>
        <Card className={styles.tableCard}>
          <div style={{ marginBottom: 16 }}>
            <Authorized authority="business:suppBusiScope:insert" noMatch={null}>
              <Button type="primary" onClick={() => router.push('/supplymanage/busiscope/add')}>
                <PlusOutlined />
                新增
              </Button>
            </Authorized>
          </div>
          <Row>
            <div>
              <StandardTable
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                loading={loading}
                data={pageData}
                rowKey="suppId"
                columns={columns}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            </div>
          </Row>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
